<template>
  <div class="addExpense app-container">
    <el-form ref="form" :model="form" :rules="roleCodeRule" label-width="120px">
      <el-row>
        <mainTilte title="基本信息" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="组合系统sku" prop="code">
            <el-input v-model.trim="form.code" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属店铺" prop="shop_id">
            <app-select v-model="form.shop_id" :disabled="isEdit" url="/shop" :params="shopParams" options-value="id" options-label="shop_name" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="中文名称" prop="name_ch">
            <el-input v-model.trim="form.name_ch" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="英文名称" prop="name_en">
            <el-input v-model="form.name_en" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="套餐单价">
            <el-input v-model.trim="price_usd" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="组合商品清单" class="mb0" />
      </el-row>
      <div class="operation_button_box">
        <el-button type="primary" @click="selectProduct">选择商品</el-button>
        <el-button type="danger" @click="delProducts">批量删除</el-button>
      </div>
      <el-table :data="form.product" stripe fit border @select="tableSelectHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column fixed="left" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" style="color: #ff4444" @click="delProduct(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="缩略图" width="150" align="center">
          <template slot-scope="scope">
            <thund :img="scope.row.image_url" />
          </template>
        </el-table-column>
        <el-table-column prop="code" label="系统sku" width="180" align="center" />
        <el-table-column prop="name_ch" label="中文名称" width="180" align="center" />
        <el-table-column prop="name_en" label="英文名称" width="180" align="center" />
        <el-table-column prop="packing_method" label="包装方式" width="180" align="center">
          <template slot-scope="scope">
            <dic-values :code="scope.row.packing_method" :dictionaries="packMethodList" />
          </template>
        </el-table-column>
        <el-table-column prop="category_text" label="商品分类" width="180" align="center" />
        <el-table-column prop="price" label="基准价" width="180" align="center" />
        <el-table-column label="数量" prop="number" min-width="180" align="center">
          <template slot-scope="scope">
            <el-form-item prop="number" class="no-label el_form_item_mar0">
              <el-input-number v-model="scope.row.number" :min="1" :precision="0" :max="999999999" placeholder="请输入数量" />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer-center">
        <span>
          <el-button :loading="btnLoading" type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="cancelProductClick">取消</el-button>
        </span>
      </div>
    </el-form>
    <!-- 添加商品 -->
    <el-dialog v-if="dialogAddProductVisible" v-loading.lock="loading" v-loading="loading" title="" :visible.sync="dialogAddProductVisible" :close-on-click-modal="false" width="90%" class="dialogText header-none" element-loading-text="正在加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center>
      <addProduct :other-params="addProductParams" :issign-contract-codes="['shop-name']" :is-product-shop="2" @checkChildIds="checkChildIds" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddProductVisible = false">取消选择</el-button>
        <el-button type="primary" @click="saveData()">确认选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import addProduct from '../components/addPortProducts'
import { validChinese, validateFirstUpperCase } from '@/utils/validate'
import dicValues from '@/components/dicTransform/index'
export default {
  components: { addProduct, dicValues },
  data() {
    return {
      form: {
        value: '',
        code: '',
        shop_id: '',
        name_ch: '',
        name_en: '',
        price_usd: '',
        product: []
      },
      packMethodList: [
        {
          code: 1,
          name: '普通商品'
        },
        {
          code: 2,
          name: '多箱包装'
        }
      ],
      roleCodeRule: {
        code: [
          { required: true, message: '请输入组合系统sku', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              validChinese(value)
                ? callback(new Error('编码须是字母，数字，非空字符组成'))
                : callback()
            },
            trigger: 'blur'
          },
          {
            max: 200,
            message: '组合系统sku必须在200个字符以内',
            trigger: 'blur'
          }
        ],
        shop_id: [
          {
            required: true,
            message: '请选择所属店铺',
            trigger: ['change', 'blur']
          }
        ],
        name_ch: [
          { required: true, message: '请输入中文名称', trigger: 'blur' },
          { max: 50, message: '中文名称必须在50个字符以内', trigger: 'blur' }
        ],
        name_en: [
          {
            validator(rule, value, callback) {
              validChinese(value)
                ? callback(new Error('英文名称不能输入中文'))
                : callback()
            },
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (value && validateFirstUpperCase(value)) {
                callback(new Error('英文名称首字母必须大写'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          },
          { max: 50, message: '英文名称必须在50个字符以内', trigger: 'blur' }
        ]
      },
      dialogAddProductVisible: false,
      loading: false,
      checkChildList: [],
      isEdit: false,
      btnLoading: false,
      selectTableList: [],
      shopParams: {
        page: 1,
        limit: 100000000,
        status: 1
      }
    }
  },
  computed: {
    price_usd() {
      const vm = this
      if (vm.form.product.length > 0) {
        const count = vm.form.product.reduce((total, ele) => {
          const price = vm.$computed.accMul(ele.number, ele.price)
          total = vm.$computed.accAdd(total, price)
          return total
        }, 0)
        return +count.toFixed(2)
      } else {
        return ''
      }
    },

    addProductParams() {
      const vm = this
      return {
        shop_id: vm.form.shop_id
      }
    }
  },
  mounted() {
    if (this.$route.query && this.$route.query.id) {
      this.isEdit = true
      this.shopParams.status = ''
      this.getDatailData(this.$route.query.id)
    }
  },
  methods: {
    // 修改店铺处理函数
    changeShopHandler(e) {
      this.form.product = []
    },
    getDatailData(id) {
      this.$http
        .get(`/productCombination/${id}`)
        .then(res => {
          if (res.code === 10000) {
            this.form = res.data
            if (res.data.list && res.data.list.length > 0) {
              this.form.product = res.data.list.map(e => {
                e['category_text'] = `${e.parent_name}-${e.category_name}`
                return e
              })
            }
            console.log(this.form, 'this.form>>>>')
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 选择商品
    selectProduct() {
      if (!this.form.shop_id) {
        return this.$message.error('请选择所属店铺')
      }
      this.dialogAddProductVisible = true
    },
    /**
     * table选择处理函数
     * */
    tableSelectHandler(e) {
      const vm = this
      vm.selectTableList = e
    },
    // 批量删除
    delProducts() {
      const vm = this
      console.log('selectTableList', vm.selectTableList)
      vm.form.product = vm.form.product.filter(ele => {
        const index = vm.selectTableList.findIndex(
          e => e.product_id === ele.product_id
        )
        return index === -1
      })
    },
    // 删除
    delProduct(index) {
      const vm = this
      vm.form.product.splice(index, 1)
    },
    cancelProductClick() {
      this.$router.push('/product/portfolioManage')
    },
    onSubmit() {
      const vm = this
      vm.$refs.form.validate(valid => {
        if (valid) {
          if (vm.form.product.length <= 0) {
            vm.$message.error('请至少选择添加一个商品')
            return
          }
          // 判断是不是 同一个店铺
          // const isevery = vm.form.product.every()
          vm.btnLoading = true
          vm.saveProductData()
        }
      })
    },
    saveProductData() {
      const params = Object.assign({}, this.form)
      params.price_usd = this.price_usd
      delete params.created_at
      delete params.updated_at
      if (this.isEdit) {
        this.$http
          .put(`/productCombination/${this.form.id}`, params)
          .then(res => {
            if (res.code === 10000) {
              this.$message.success('修改成功')
              this.$router.push('/product/portfolioManage')
            }
            this.btnLoading = false
          })
          .catch(() => {
            this.btnLoading = false
          })
      } else {
        this.$http
          .post(`/productCombination`, params)
          .then(res => {
            if (res.code === 10000) {
              this.$message.success('新增成功')
              this.$router.push('/product/portfolioManage')
            }
            this.btnLoading = false
          })
          .catch(() => {
            this.btnLoading = false
          })
      }
    },
    // 确认选择
    saveData() {
      const dataLength = this.checkChildList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      const firstShopId = this.checkChildList[0].shop_id
      const isSameShopId = this.checkChildList.every(
        e => e.shop_id === firstShopId
      )
      if (!isSameShopId) {
        this.$message.error('所选择的数据必须所属同一个店铺')
        return
      }
      // this.form.shop_id = this.checkChildList[0].shop_id

      this.checkChildList.forEach(ele => {
        const index = this.form.product.findIndex(
          e => e.product_id === ele.product_id
        )
        if (index > -1) {
          this.form.product.splice(index, 1)
        }
        const productObj = {
          image_url: ele.image_url,
          code: ele.product_code ?? ele.code,
          packing_method: ele.packing_method,
          product_id: ele.product_id ?? ele.id,
          name_ch: ele.name_ch,
          name_en: ele.name_en,
          type: ele.type === 0 ? '内部员工' : '客户商品', // 商品所属客户类型 0-内部员工 1-客户商品
          category_name: ele.category_name, // 商品分类
          category_text: ele.category_text, // 商品分类
          price: ele.type === 0 ? ele.benchmark_price : ele.purchase_price_usd, // 基准价
          number: ''
        }
        if (!this.form.product.some(v => v.product_id === productObj.product_id)) {
          this.form.product.push(productObj)
        }

      })
      this.dialogAddProductVisible = false
    },
    checkChildIds(data) {
      this.checkChildList = data
    }
  }
}
</script>

<style scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}
/deep/.el-select,
.el-autocomplete {
  width: 100%;
}
.sizeStyle {
  display: flex;
}
.sizeStyle /deep/ .el-input__inner {
  border-right: 0;
}
.sizeStyle /deep/ .el-input-group__append {
  padding-left: 4px;
  padding-right: 4px;
  font-size: 14px;
  color: #333333;
  background: #fff;
}
</style>
